package com.example.mytips.assets;

import com.example.mytips.utils.TextInsertUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.WrapLayout;
import groovyjarjarantlr4.v4.runtime.misc.Nullable;
import org.apache.http.util.TextUtils;
import org.jetbrains.annotations.NonNls;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.List;

import static org.mozilla.javascript.ScriptRuntime.add;

public class FlutterAssetsDialog extends DialogWrapper {

    private int groupWidth = 200;

    private int width = 850;
    private int height = 2024;

    private VirtualFile[] subDirs;
    private JBList<String> subDirList;

    private VirtualFile assetsDir;

    private JBScrollPane leftPanel;

    private JBScrollPane rightPanel;

    private String basePath;

    private String selectPath;

    private AnActionEvent e;

    private JPanel gridPanel;

    private GridBagConstraints gbc;

    public FlutterAssetsDialog(AnActionEvent e, VirtualFile[] subDirs, VirtualFile assetsDir, String basePath) {
        super(true);
        this.subDirs = subDirs;
        this.assetsDir = assetsDir;
        this.basePath = basePath;
        this.e = e;

        // 创建左侧子目录列表
        String[] subDirNames = Arrays.stream(subDirs)
                .map(VirtualFile::getName)
                .toArray(String[]::new);
        subDirList = new JBList<>(subDirNames);
        subDirList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        subDirList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                ///每次点击都初始化一下
                gridPanel.removeAll();
                gbc.gridx = 0;
                gbc.gridy = 0;

                if (e.getClickCount() == 1) {
                    // 获取子目录名称
                    String selectedSubDir = subDirList.getSelectedValue();
                    // 获取选中目录下的所有图片文件
                    VirtualFile child = assetsDir.findChild(selectedSubDir);
                    if (child != null) {
                        VirtualFile[] imageFiles = child.getChildren();

                        //将图片文件路径转换为字符串数组
                        String[] imagePaths = Arrays.stream(imageFiles)
                                .map(VirtualFile::getPath)
                                .toArray(String[]::new);

                        for (int i = 0; i < imagePaths.length; i++) {
                            String value = imagePaths[i];

                            ImageIcon imageIcon = new ImageIcon(value);

                            Image image = imageIcon.getImage();
                            int width = image.getWidth(null);
                            int height = image.getHeight(null);

                            Image scaledInstance = image.getScaledInstance(100, 100 * height / width, Image.SCALE_SMOOTH);
                            imageIcon = new ImageIcon(scaledInstance);


                            JLabel label = new JLabel(imageIcon);
                            label.setOpaque(true);

                            // 添加MouseListener来监听点击事件
                            label.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    label.setBorder(BorderFactory.createLineBorder(Color.RED));
                                    selectPath = value.replace(basePath, "");
                                }
                            });

                            gridPanel.add(label, gbc);

                            gbc.gridx++; // 控制列数，每次添加后将x坐标加1
                            if (gbc.gridx == 5) { // 当达到3列时换行
                                gbc.gridx = 0;
                                gbc.gridy++;
                            }
                        }

                        // 重新布局和绘制组件
                        gridPanel.revalidate();
                        gridPanel.repaint();
                    }
                }
            }
        });

        leftPanel = new JBScrollPane(subDirList);
        leftPanel.setPreferredSize(new Dimension(groupWidth, height));

        // 创建一个JPanel来放置网格布局
        gridPanel = new JPanel();
        gridPanel.setLayout(new GridBagLayout());

        // 创建一个GridBagConstraints来控制组件的位置和大小
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.NORTH; // 设置组件在垂直方向上顶部对齐

        // 创建一个JScrollPane，并将gridPanel放置在其中
        rightPanel = new JBScrollPane(gridPanel);
        rightPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        rightPanel.setPreferredSize(new Dimension(width - groupWidth, height));

        // 设置对话框界面布局
        setTitle("项目图片资源");
        // 固定窗口大小
        setResizable(false);
        // 窗口大小
        setSize(width, height);
        // 设置尺寸后，立马执行这个
        pack();
        // 初始化对话框内容
        init();

    }

    @Override
    protected @NonNls @org.jetbrains.annotations.Nullable String getDimensionServiceKey() {
        return "FlutterAssetsDialog";
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        // 创建中心面板
        JBPanel centerPanel = new JBPanel(new BorderLayout());
        // 添加左侧面板和右侧面板到中心面板
        centerPanel.add(leftPanel, BorderLayout.WEST);
        centerPanel.add(rightPanel, BorderLayout.CENTER);

        return centerPanel;
    }

    @Override
    protected void doOKAction() {
        // 在这里处理确定按钮的事件
        System.out.println("选中的地址 = " + selectPath);

        if (TextUtils.isEmpty(selectPath)) return;

        // 在光标插入 selectPath
        TextInsertUtil.insertString(e, "\"" + selectPath + "\"");

        super.doOKAction();
    }
}